<template>
  <div class="teaching-mission-score">
    <div class="page-header">
      <h1>成绩</h1>
      <div class="actions">
        <el-button @click="goBack">
          <el-icon><ArrowLeft /></el-icon> 返回
        </el-button>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <!-- 教学任务信息 -->
    <el-card v-if="missionInfo" class="mission-info">
      <template #header>
        <span>教学任务信息</span>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="课程名称">{{ missionInfo.courseName }}</el-descriptions-item>
        <el-descriptions-item label="学期">{{ missionInfo.termName }}</el-descriptions-item>
        <el-descriptions-item label="授课教师">{{ missionInfo.teacherNames ? missionInfo.teacherNames.join(', ') : '' }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ missionInfo.majorNames ? missionInfo.majorNames.join(', ') : '' }}</el-descriptions-item>
        <el-descriptions-item label="培养层次">{{ missionInfo.cengCiNames ? missionInfo.cengCiNames.join(', ') : '' }}</el-descriptions-item>
        <el-descriptions-item label="学员人数">{{ studentsData.length }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button 
            type="primary" 
            @click="showImportDialog"
            :disabled="!scoreComponents || scoreComponents.length === 0"
          >
            <el-icon><Upload /></el-icon> 导入成绩
          </el-button>
          <el-tooltip 
            :content="getDownloadTemplateTooltip()" 
            placement="top"
            :disabled="scoreComponents && scoreComponents.length > 0 && studentsData && studentsData.length > 0"
          >
            <el-button 
              @click="downloadTemplate"
              :disabled="!scoreComponents || scoreComponents.length === 0 || !studentsData || studentsData.length === 0"
            >
              <el-icon><Download /></el-icon> 下载模板
            </el-button>
          </el-tooltip>
          <el-button @click="exportScores">
            <el-icon><Download /></el-icon> 导出成绩
          </el-button>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button 
            type="success" 
            @click="calculateFinalScores"
            :disabled="!scoreComponents || scoreComponents.length === 0"
          >
            <el-icon><DataAnalysis /></el-icon> 计算最终成绩
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 考核组成未设置时的提示 -->
    <el-alert
      v-if="!scoreComponents || scoreComponents.length === 0"
      title="考核组成未设置"
      type="warning"
      description="该教学任务尚未设置考核组成，请先前往考核组成管理页面设置考核方案后再进行成绩录入。"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    />

    <!-- 学员未分配时的提示 -->
    <el-alert
      v-else-if="!studentsData || studentsData.length === 0"
      title="学员未分配"
      type="warning"
      description="该教学任务尚未分配学员，请先分配学员后再进行成绩录入。"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    />

    <!-- 学员成绩表格 -->
    <el-card class="score-table">
      <el-table :data="studentsData" v-loading="loading" style="width: 100%" border>
        <el-table-column prop="studentId" label="学号" width="120" resizable />
        <el-table-column prop="name" label="姓名" width="100" resizable />
        <el-table-column prop="className" label="班级" width="120" resizable />
        <el-table-column prop="majorName" label="专业" width="150" resizable />
        
        <!-- 动态生成考核组成部分列 -->
        <template v-for="component in scoreComponents" :key="component.id">
          <el-table-column :label="component.name" :prop="'partScore_' + component.id" width="100">
            <template #default="scope">
              <span v-if="getPartScore(scope.row.studentId, component.id) !== null">
                {{ getPartScore(scope.row.studentId, component.id) }}
              </span>
              <span v-else class="text-gray">未录入</span>
            </template>
          </el-table-column>
        </template>
        
        <!-- 最终成绩列 -->
        <el-table-column prop="finalScore" label="最终成绩" width="100" resizable>
          <template #default="scope">
            <span v-if="scope.row.finalScore !== null && scope.row.finalScore !== undefined">
              {{ scope.row.finalScore }}
            </span>
            <span v-else class="text-gray">未录入</span>
          </template>
        </el-table-column>
        <el-table-column prop="isPass" label="是否通过" width="100" resizable>
          <template #default="scope">
            <el-tag 
              v-if="scope.row.isPass !== null && scope.row.isPass !== undefined"
              :type="scope.row.isPass ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.isPass ? '通过' : '不通过' }}
            </el-tag>
            <span v-else class="text-gray">未设置</span>
          </template>
        </el-table-column>
        <el-table-column prop="isMakeup" label="是否补考" width="100" resizable>
          <template #default="scope">
            <el-tag 
              v-if="scope.row.isMakeup"
              type="warning"
              size="small"
            >
              补考
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" resizable>
          <template #default="scope">
            <el-button size="small" @click="editScore(scope.row)">
              编辑成绩
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 导入成绩对话框 -->
    <el-dialog 
      v-model="importDialogVisible" 
      title="导入成绩" 
      width="500px"
      :close-on-click-modal="false"
      @close="handleCloseImportDialog"
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :on-exceed="handleExceed"
        accept=".xlsx,.xls"
        :limit="1"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传xlsx/xls文件，且不超过10MB<br/>
            <span style="color: #E6A23C; font-weight: bold;">
              ⚠️ 重要提醒：请先删除模板底部的说明行再导入
            </span>
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport" :loading="importing" :disabled="!canImport">
            确认导入
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑成绩对话框 -->
    <el-dialog 
      v-model="editScoreDialogVisible" 
      title="编辑成绩" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="editScoreForm" label-width="120px">
        <el-form-item label="学号">
          <el-input v-model="editScoreForm.studentId" disabled />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editScoreForm.studentName" disabled />
        </el-form-item>
        
        <!-- 动态成绩组成 -->
        <template v-for="component in scoreComponents" :key="component.id">
          <el-form-item :label="component.name">
            <el-input-number 
              v-model="editScoreForm.partScores[component.id]" 
              :min="0" 
              :max="100" 
              :precision="1"
              style="width: 100%"
            />
          </el-form-item>
        </template>
        
        <el-divider content-position="center">最终成绩（系统自动计算）</el-divider>
        
        <el-form-item label="最终成绩">
          <el-input 
            :value="calculatedFinalScore" 
            disabled
            placeholder="保存单项成绩后自动计算"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否通过">
          <el-input 
            :value="calculatedIsPass" 
            disabled
            placeholder="根据最终成绩自动判定"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否补考">
          <el-switch v-model="editScoreForm.isMakeup" disabled />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editScoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveScore" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ArrowLeft, 
  Refresh, 
  Upload, 
  Download, 
  DataAnalysis,
  UploadFilled 
} from '@element-plus/icons-vue';
import { 
  getTeachingMissionStudents,
  exportStudentScores,
  importStudentScores
} from '@/api/teaching-mission';
import { teachingMissionApi } from '@/api/teaching-mission';
import { scoreApi, scoreComponentApi } from '@/api/score';
import request from '@/api/request';

export default {
  name: 'TeachingMissionScore',
  components: {
    ArrowLeft,
    Refresh,
    Upload,
    Download,
    DataAnalysis,
    UploadFilled
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    // 状态管理
    const loading = ref(false);
    const importing = ref(false);
    const saving = ref(false);
    
    // 数据
    const missionId = ref(route.query.missionId);
    const missionInfo = ref(null);
    const studentsData = ref([]);
    const scoreComponents = ref([]);
    const partScores = ref([]);
    
    // 导入对话框
    const importDialogVisible = ref(false);
    const selectedFile = ref(null);
    const uploadRef = ref();
    
    // 计算属性：是否可以导入
    const canImport = computed(() => {
      if (!selectedFile.value) return false;
      
      // 检查是否有有效的文件对象
      const file = selectedFile.value.raw || selectedFile.value;
      const isValid = file && (file instanceof File || (file.name && file.size !== undefined));
      return isValid;
    });
    
    // 编辑成绩对话框
    const editScoreDialogVisible = ref(false);
    const editScoreForm = ref({
      studentId: '',
      studentName: '',
      finalScore: null,
      isPass: null,
      isMakeup: false,
      partScores: {}
    });

    // 计算最终成绩
    const calculatedFinalScore = computed(() => {
      if (!scoreComponents.value || scoreComponents.value.length === 0) {
        return '';
      }
      
      let totalWeightedScore = 0;
      let totalWeight = 0;
      
      for (const component of scoreComponents.value) {
        const score = editScoreForm.value.partScores[component.id];
        if (score !== null && score !== undefined && score !== '') {
          totalWeightedScore += score * (component.proportion / 100);
          totalWeight += component.proportion / 100;
        }
      }
      
      if (totalWeight === 0) {
        return '';
      }
      
      // 如果总权重不等于1，按比例调整
      const finalScore = totalWeight === 1 ? totalWeightedScore : (totalWeightedScore / totalWeight);
      return finalScore.toFixed(1);
    });

    // 计算是否通过
    const calculatedIsPass = computed(() => {
      const score = parseFloat(calculatedFinalScore.value);
      if (isNaN(score)) {
        return '';
      }
      return score >= 60 ? '通过' : '不通过';
    });

    // 获取教学任务信息
    const fetchMissionInfo = async () => {
      if (!missionId.value) return;
      
      try {
        const response = await teachingMissionApi.getTeachingMissionById(missionId.value);
        missionInfo.value = response;
      } catch (error) {
        ElMessage.error('获取教学任务信息失败');
      }
    };

    // 获取学员数据
    const fetchStudentsData = async () => {
      if (!missionId.value) return;
      
      loading.value = true;
      try {
        const students = await getTeachingMissionStudents(missionId.value);
        studentsData.value = students || [];
      } catch (error) {
        ElMessage.error('获取学员数据失败');
        studentsData.value = [];
      } finally {
        loading.value = false;
      }
    };

    // 获取成绩组成
    const fetchScoreComponents = async () => {
      if (!missionId.value) return;
      
      try {
        const components = await scoreComponentApi.getScoreComponentsByTeachingMission(missionId.value);
        scoreComponents.value = components || [];
      } catch (error) {
        ElMessage.error('获取成绩组成失败');
        scoreComponents.value = [];
      }
    };
    
    // 获取部分成绩
    const fetchPartScores = async () => {
      if (!missionId.value) return;
      
      try {
        const scores = await scoreApi.getPartScoresByTeachingMission(missionId.value);
        partScores.value = scores || [];
      } catch (error) {
        ElMessage.error('获取部分成绩失败');
        partScores.value = [];
      }
    };

    // 刷新数据
    const refreshData = async () => {
      await Promise.all([
        fetchMissionInfo(),
        fetchStudentsData(),
        fetchScoreComponents(),
        fetchPartScores()
      ]);
    };

    // 返回
    const goBack = () => {
      router.back();
    };

    // 显示导入对话框
    const showImportDialog = () => {
      selectedFile.value = null;
      importDialogVisible.value = true;
      // 清空上传组件
      nextTick(() => {
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }
      });
    };

    // 文件选择处理
    const handleFileChange = (file, fileList) => {
      if (file) {
        // Element Plus 上传组件在不同情况下可能返回不同的文件对象结构
        selectedFile.value = file.raw ? file : { raw: file };
      } else {
        selectedFile.value = null;
      }
    };

    // 文件移除处理
    const handleFileRemove = (file, fileList) => {
      selectedFile.value = null;
    };

    // 文件超出限制处理
    const handleExceed = () => {
      ElMessage.warning('只能选择一个文件');
    };

    // 关闭导入对话框
    const handleCloseImportDialog = () => {
      selectedFile.value = null;
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    };

    // 确认导入
    const confirmImport = async () => {
      if (!selectedFile.value) {
        ElMessage.warning('请选择要导入的文件');
        return;
      }

      const file = selectedFile.value.raw || selectedFile.value;
      const formData = new FormData();
      formData.append('file', file);
      formData.append('teachingMissionId', missionId.value);

      importing.value = true;
      try {
        const result = await importStudentScores(formData);
        
        // 显示详细的导入结果
        const successMsg = `导入完成！新增${result.successCount || 0}条，更新${result.updatedCount || 0}条，失败${result.errorCount || 0}条`;
        if (result.duplicateCount > 0) {
          successMsg += `，跳过重复${result.duplicateCount}条`;
        }
        
        if (result.errorCount === 0 && result.duplicateCount === 0) {
          ElMessage.success(successMsg);
        } else {
          ElMessage.warning(successMsg);
        }
        
        // 处理错误和重复信息
        if (result.errorCount > 0 || result.duplicateCount > 0) {
          await showImportReport(result);
        }
        
        importDialogVisible.value = false;
        selectedFile.value = null;
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }
        
        // 导入完成后刷新所有相关数据
        await refreshData();
      } catch (error) {
        ElMessage.error(`导入成绩失败: ${error.response?.data?.message || error.message || '未知错误'}`);
      } finally {
        importing.value = false;
      }
    };

    // 显示导入报告
    const showImportReport = async (result) => {
      let reportContent = '';
      
      if (result.errors && result.errors.length > 0) {
        reportContent += '<h4 style="color: #e74c3c; margin-bottom: 10px;">❌ 导入错误 (' + result.errors.length + '条)</h4>';
        reportContent += '<div style="max-height: 200px; overflow-y: auto; margin-bottom: 15px;">';
        result.errors.forEach(error => {
          reportContent += `<p style="margin: 5px 0; padding: 5px; background: #ffeaea; border-left: 3px solid #e74c3c;">`;
          reportContent += `<strong>第${error.row}行</strong> (学号: ${error.studentId || '未知'})<br/>`;
          reportContent += `<span style="color: #666;">类型: ${getErrorTypeText(error.errorType)}</span><br/>`;
          reportContent += `<span style="color: #e74c3c;">${error.message}</span><br/>`;
          if (error.suggestion) {
            reportContent += `<span style="color: #3498db; font-size: 12px;">💡 建议: ${error.suggestion}</span>`;
          }
          reportContent += '</p>';
        });
        reportContent += '</div>';
      }
      
      if (result.duplicates && result.duplicates.length > 0) {
        reportContent += '<h4 style="color: #f39c12; margin-bottom: 10px;">⚠️ 重复处理 (' + result.duplicates.length + '条)</h4>';
        reportContent += '<div style="max-height: 200px; overflow-y: auto;">';
        result.duplicates.forEach(duplicate => {
          reportContent += `<p style="margin: 5px 0; padding: 5px; background: #fff8e1; border-left: 3px solid #f39c12;">`;
          reportContent += `<strong>${duplicate.studentId}</strong> (${duplicate.studentName})<br/>`;
          reportContent += `原成绩: <span style="color: #666;">${duplicate.oldScore}</span> → 新成绩: <span style="color: #2196f3;">${duplicate.newScore}</span><br/>`;
          reportContent += `<span style="color: ${duplicate.action === 'updated' ? '#4caf50' : '#ff9800'};">`;
          reportContent += duplicate.action === 'updated' ? '✅ 已更新' : '⏭️ 已跳过';
          reportContent += '</span>';
          reportContent += '</p>';
        });
        reportContent += '</div>';
      }
      
      await ElMessageBox.alert(reportContent, '导入详细报告', {
        type: 'info',
        customClass: 'import-report-dialog',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认'
      });
    };

    // 获取错误类型文本
    const getErrorTypeText = (errorType) => {
      const typeMap = {
        'FILE_FORMAT': '文件格式错误',
        'DUPLICATE_IN_FILE': '文件内重复',
        'VALIDATION_ERROR': '数据验证错误',
        'STUDENT_NOT_FOUND': '学生不存在',
        'SYSTEM_ERROR': '系统错误'
      };
      return typeMap[errorType] || errorType;
    };

    // 下载模板
    const downloadTemplate = async () => {
      // 检查考核组成是否已设置
      if (!scoreComponents.value || scoreComponents.value.length === 0) {
        ElMessage({
          message: '该教学任务尚未设置考核组成，无法生成成绩导入模板。请先前往"考核组成管理"页面设置考核方案。',
          type: 'warning',
          duration: 5000,
          showClose: true
        });
        return;
      }

      // 检查是否有学生
      if (!studentsData.value || studentsData.value.length === 0) {
        ElMessage({
          message: '该教学任务尚未分配学生，无法生成成绩导入模板。请先分配学生再下载模板。',
          type: 'warning',
          duration: 5000,
          showClose: true
        });
        return;
      }

      try {
        const response = await request({
          url: `/api/teaching-missions/${missionId.value}/template/download-scores`,
          method: 'get',
          responseType: 'blob'
        });
        
        // 创建下载链接
        const blob = new Blob([response.data], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '成绩导入模板.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        ElMessage({
          message: '模板下载成功！请注意：填写完成绩后，导入前请删除模板底部的说明行。',
          type: 'success',
          duration: 8000,
          showClose: true
        });
      } catch (error) {
        
        // 优化错误提示，根据具体错误内容提供更友好的信息
        let errorMessage = '下载模板失败';
        
        if (error.response) {
          // 尝试解析错误响应
          try {
            const errorText = await error.response.text();
            if (errorText.includes('尚未设置考核组成')) {
              errorMessage = '该教学任务尚未设置考核组成，无法生成成绩导入模板。请先前往"考核组成管理"页面设置考核方案。';
            } else if (errorText.includes('尚未分配学生')) {
              errorMessage = '该教学任务尚未分配学生，无法生成成绩导入模板。请先分配学生再下载模板。';
            } else if (errorText.includes('教学任务不存在')) {
              errorMessage = '教学任务不存在，请检查任务信息是否正确。';
            }
          } catch (parseError) {
          }
        }
        
        ElMessage({
          message: errorMessage,
          type: 'error',
          duration: 5000,
          showClose: true
        });
      }
    };

    // 导出成绩
    const exportScores = async () => {
      try {
        await exportStudentScores(missionId.value);
        ElMessage.success('导出成功');
      } catch (error) {
        ElMessage.error('导出成绩失败');
      }
    };

    // 计算最终成绩
    const calculateFinalScores = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要重新计算所有学员的最终成绩吗？此操作将根据成绩组成配置自动计算。',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        loading.value = true;
        await scoreApi.calculateFinalScores(missionId.value);
        ElMessage.success('最终成绩计算完成');
        await fetchStudentsData();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('计算最终成绩失败');
        }
      } finally {
        loading.value = false;
      }
    };

    // 编辑成绩
    const editScore = (student) => {
      // 初始化部分成绩
      const partScoresObj = {};

      // 填充已有的部分成绩
      scoreComponents.value.forEach(component => {
        const score = partScores.value.find(
          s => s.studentId === student.id && s.scoreComponentId === component.id
        );
        partScoresObj[component.id] = score ? score.score : null;
      });

      editScoreForm.value = {
        id: student.id, // 添加学生的数据库ID
        studentId: student.studentId,
        studentName: student.name,
        finalScore: student.finalScore,
        isPass: student.isPass,
        isMakeup: student.isMakeup || false,
        partScores: partScoresObj
      };
      editScoreDialogVisible.value = true;
    };

    // 保存成绩
    const saveScore = async () => {
      saving.value = true;
      try {
        // 只保存部分成绩，最终成绩由后端自动计算
        const partScorePromises = [];
        for (const componentId in editScoreForm.value.partScores) {
          if (editScoreForm.value.partScores[componentId] !== null && 
              editScoreForm.value.partScores[componentId] !== undefined &&
              editScoreForm.value.partScores[componentId] !== '') {
            const partScoreData = {
              teachingMissionId: missionId.value,
              studentId: editScoreForm.value.id, // 使用学生的数据库ID
              scoreComponentId: Number(componentId),
              score: editScoreForm.value.partScores[componentId]
            };
            partScorePromises.push(scoreApi.createOrUpdatePartScore(partScoreData));
          }
        }

        // 执行所有单项成绩保存请求
        if (partScorePromises.length > 0) {
          await Promise.all(partScorePromises);
          ElMessage.success('成绩保存成功，系统已自动计算最终成绩');
        } else {
          ElMessage.warning('没有有效的成绩数据需要保存');
        }
        
        editScoreDialogVisible.value = false;
        
        // 刷新学生数据和部分成绩数据以显示最新的计算结果
        await Promise.all([
          fetchStudentsData(),
          fetchPartScores()
        ]);
      } catch (error) {
        ElMessage.error('保存成绩失败');
      } finally {
        saving.value = false;
      }
    };

    // 强制刷新 studentsData 和 partScores 数据
    studentsData.value = [...studentsData.value];
    partScores.value = [...partScores.value];

    // 获取部分成绩
    const getPartScore = (studentId, componentId) => {
      // 先找到对应学号的学生对象，获取其数据库ID
      const student = studentsData.value.find(s => s.studentId === studentId);
      if (!student) return null;
      
      // 使用学生的数据库ID去匹配部分成绩
      const score = partScores.value.find(
        score => score.studentId === student.id && score.scoreComponentId === componentId
      );
      return score ? score.score : null;
    };

    // 获取下载模板按钮的提示信息
    const getDownloadTemplateTooltip = () => {
      if (!scoreComponents.value || scoreComponents.value.length === 0) {
        return '该教学任务尚未设置考核组成，请先前往考核组成管理页面设置考核方案';
      }
      if (!studentsData.value || studentsData.value.length === 0) {
        return '该教学任务尚未分配学生，请先分配学生再下载模板';
      }
      return '';
    };

    // 页面初始化
    onMounted(async () => {
      if (!missionId.value) {
        ElMessage.error('缺少教学任务ID参数');
        router.back();
        return;
      }
      
      await refreshData();
    });

    return {
      loading,
      importing,
      saving,
      missionInfo,
      studentsData,
      scoreComponents,
      partScores,
      importDialogVisible,
      selectedFile,
      canImport,
      uploadRef,
      editScoreDialogVisible,
      editScoreForm,
      calculatedFinalScore,
      calculatedIsPass,
      refreshData,
      goBack,
      showImportDialog,
      handleFileChange,
      handleFileRemove,
      handleExceed,
      handleCloseImportDialog,
      confirmImport,
      showImportReport,
      getErrorTypeText,
      downloadTemplate,
      exportScores,
      calculateFinalScores,
      editScore,
      saveScore,
      getPartScore,
      getDownloadTemplateTooltip
    };
  }
};
</script>

<style scoped>
.teaching-mission-score {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  display: flex;
  gap: 10px;
}

.mission-info {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.score-table {
  margin-bottom: 20px;
}

.text-gray {
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.import-error-dialog) {
  white-space: pre-line;
  max-height: 400px;
  overflow-y: auto;
}

:deep(.import-report-dialog) {
  max-width: 80%;
}

:deep(.import-report-dialog .el-message-box__content) {
  max-height: 500px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .toolbar :deep(.el-col) {
    margin-bottom: 10px;
  }
}
</style>